package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.HabitusDao;
import com.itheima.dao.QuestionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Habitus;
import com.itheima.pojo.Member;
import com.itheima.service.HabitusService;
import com.itheima.utils.HabitusUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = HabitusService.class)
@Transactional
public class HabitusServiceImpl implements HabitusService {

    @Autowired
    private HabitusDao habitusDao;

    @Autowired
    private QuestionDao questionDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        Page<Map<String,Object>> page = habitusDao.findByHabitusCondition(queryPageBean.getQueryString());

        List<Map<String, Object>> result = page.getResult();

        for (Map<String, Object> report : result) {
           List<Habitus> habituses = (List<Habitus>)report.get("habituses");
            Map<Object, Object> hashMap = new HashMap<>();
            for (Habitus habitus : habituses) {
                hashMap.put(habitus.getName(),habitus.getStatus());
            }
            report.put("habituses",hashMap);
        }

        return new PageResult(page.getTotal(),result);
    }

    @Override
    public List<Habitus> findFormData() {
        return habitusDao.findAllHabitus();
    }

    @Override
    public void addReport(List<Habitus> habituses, Integer id) {
        //计算体质
        List<Habitus> compute = HabitusUtils.compute(habituses);
        //添加Report表,并返回自增主键
        Map<String, Object> report = new HashMap<>();
        report.put("mamberId",id);
        habitusDao.insertReport(report);
        Integer rid = (Integer) report.get("id");
        System.out.println(rid);

        //添加体质数据
        habitusDao.insertHabitusStatus(habituses,rid);
        //添加问题数据
        for (Habitus habitus : habituses) {
            questionDao.insertQuestionScore(habitus.getQuestions(),rid);
        }

    }

    @Override
    public void deleteReport(Integer id) {
        //删除体质数据
        habitusDao.deleteStatusByRid(id);
        //删除问卷数据
        questionDao.deleteScoreByrid(id);
        //删除报告记录
        habitusDao.deleteReportByid(id);
    }

    @Override
    public Map<String, Object> findOneById(Integer id) {
        return habitusDao.findOneReportById(id);
    }

    @Override
    public void updateHabitusStatus(List<Habitus> habitus, int id) {
        habitusDao.updateHabitusStatus(habitus,id);
    }


}
